qx.Class.define("mutual.ow.ABM",
{
	extend : qx.ui.core.Widget,
	construct : function (json, serviceNameApp, title, async)
	{
		this._json = json;
		this._serviceNameApp = serviceNameApp;
		this._async = async;
		this.base(arguments);

		this._setLayout(new qx.ui.layout.Basic());

		this._grpLayer = new qx.ui.groupbox.GroupBox(title);

		this._grpLayer.setLayout(new qx.ui.layout.Basic());

		this._grpInterface = new qx.ui.groupbox.GroupBox();
		this._grpInterface.setLayout(new qx.ui.layout.VBox(5));

		this._w = new Array();
		this._constructInterface();
		this._constructGrid();
		this._constructValues();
		this._constructEvents();
		this._initWidget();
	},
	members :
	{
		_json : null,
		_serviceNameApp : null,
		_w : null,
		_grpLayer : null,
		_grpInterface : null,
		_grpAcciones : null,
		_grpOpciones : null,
		_grpGrid : null,
		_grpLayer : null,
		_grid : null,
		_async : null,
		setAsync : function (value) {
			this._async = value;
		},
		_initWidget : function ()
		{
			this._grpInterface.hide();
			this._grpGrid.show();
			if (this._w[this._json.key].classname === "qx.core.Object")
			{
				this._w[this._json.key].setUserData(this._json.key, "");
			}
			if (this._json[this._json.key].object != undefined)
			{
				this._w[this._json.key].setEnabled(true);
			}
			for (var obj in this._json)
			{
				if (this._json[obj].object != undefined)
				{
					this._w[obj].setValue("");
				}
			}
			this._getValuesGrid();
		},
		_constructInterface : function ()
		{
			for (var obj in this._json)
			{
				if (this._json[obj].object != undefined)
				{
					if (this._json[obj].label != undefined)
					{
						this._w[obj] = this._json[obj].object;
						var tmp = new qx.ui.container.Composite(new qx.ui.layout.HBox(1));
						tmp.add(new qx.ui.basic.Label(this._json[obj].label).set({width:120}));
						tmp.add(this._w[obj].set({width:200}));
						this._grpInterface.add(tmp);
						tmp = null;
					}
					else
					{
						this._w[obj] = this._json[obj].object;
						this._grpInterface.add(this._w[obj]);
					}
				}

				if (this._json.key != undefined)
				{
					if (this._json[this._json.key].object == undefined)
					{
						this._w[this._json.key] = new qx.core.Object;
					}
				}
			}
			this._grpAcciones = new qx.ui.groupbox.GroupBox();
			this._grpAcciones.setLayout(new qx.ui.layout.HBox(20).set({alignX:"center"}));
			this._w["btnGuardar"] = new qx.ui.form.Button("Guardar");
			this._w["btnCancelar"] = new qx.ui.form.Button("Cancelar");

			this._grpAcciones.add(this._w["btnGuardar"]);
			this._grpAcciones.add(this._w["btnCancelar"]);
			this._grpInterface.add(this._grpAcciones);

			this._add(this._grpInterface, {left:0, top:0});
		},
		_constructGrid : function ()
		{
			var conFiltro = new qx.ui.container.Composite(new qx.ui.layout.HBox(10));
			this._txtFiltro = new qx.ui.form.TextField().set({width:200});
			
			var columnasFiltro = new Array();
			var col = 0;
			var filter = new Array();
			for (var obj in this._json) // For para el armado de COLUMNAS
			{
				if (this._json[obj].tableView != undefined)
				{
					col++;
					filter[col-1] = false;
					if ((this._json[obj].tableView.visible != false) && ((this._json[obj].tableView.visible) || (this._json[obj].tableView.visible == undefined)))
					{
						filter[col-1] = true;
						columnasFiltro.push({value : col-1, label : this._json[obj].tableView.label});
					}
				}
			}
			
			this._cmbFiltro = new mutual.ow.ComboBox("Filtrar:", columnasFiltro);
				this._cmbFiltro.getLabel().setWidth(50);
			conFiltro.add(new qx.ui.basic.Label("Buscar:"));
			conFiltro.add(this._txtFiltro);
			conFiltro.add(this._cmbFiltro);
			
			this._txtFiltro.addListener("input", function (e)
			{
				this.__txtBuscar = e.getData();
				this.__timerBuscar.restart();
			}, this);
			
			this._cmbFiltro.addListener("changeValue", function ()
			{
				this.__timerBuscar.restart();
			}, this);
			
			this.__Timeout = 250;
			this.__txtBuscar = "";
			this.__timerBuscar = new qx.event.Timer(this.__Timeout);
			this.__timerBuscar.addListener('interval', function(e)
			{
				this.__timerBuscar.stop();
				if(this.__txtBuscar == "")
				{
					this._grid.getTableModel().setView(0);
				}
				else
				{
					this._grid.getTableModel().updateView(this._cmbFiltro.getValue());
					this._grid.getTableModel().setView(this._cmbFiltro.getValue());
				}
			}, this);

			var model = new mutual.ow.Smart();
			
			for (var i=0; i <= (col-1); i++)
			{
				if (filter[i])
				{
					switch (i)
					{
						case 0:	model.addView(function (rowdata) {return ((rowdata[0] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 1:	model.addView(function (rowdata) {return ((rowdata[1] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 2:	model.addView(function (rowdata) {return ((rowdata[2] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 3:	model.addView(function (rowdata) {return ((rowdata[3] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 4:	model.addView(function (rowdata) {return ((rowdata[4] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 5:	model.addView(function (rowdata) {return ((rowdata[5] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 6:	model.addView(function (rowdata) {return ((rowdata[6] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 7:	model.addView(function (rowdata) {return ((rowdata[7] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 8:	model.addView(function (rowdata) {return ((rowdata[8] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 9:	model.addView(function (rowdata) {return ((rowdata[9] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
						case 10:model.addView(function (rowdata) {return ((rowdata[10] + "").toLowerCase().indexOf(this.__txtBuscar.toString().toLowerCase()) != -1); }, this); break;
					}
				}
			}
			
			var columnas = new Array();
			for (var obj in this._json) // For para el armado de COLUMNAS
			{
				if (this._json[obj].tableView != undefined)
				{
					columnas.push(this._json[obj].tableView.label);
				}
			}
			model.setColumns(columnas);
			columnas = null;

			this._grid = new qx.ui.table.Table(model);
			this._grid.setShowCellFocusIndicator(true);
			
			if (this._json.tableWidth != undefined)
				this._grid.setWidth(this._json.tableWidth);
            else
				this._grid.setWidth(500);

			if (this._json.tableWidth != undefined)
				this._grid.setHeight(this._json.tableHeight);
            else
				this._grid.setHeight(200);
				
			this._grid.setStatusBarVisible(false);

			var i = 0;
			for (var obj in this._json) // For que identifica las propiedades de cada columna
			{
				if (this._json[obj].tableView != undefined)
				{
					if (this._json[obj].tableView.visible === false) this._grid.getTableColumnModel().setColumnVisible(i, false);
					if (this._json[obj].tableView.width != undefined) this._grid.setColumnWidth(i, this._json[obj].tableView.width);
					
					i++;
				}
			}
			i = null;
			
			this._grpGrid = new qx.ui.groupbox.GroupBox();
			this._grpGrid.setLayout(new qx.ui.layout.VBox(5));
			this._grpGrid.add(conFiltro);
			this._grpGrid.add(this._grid);
			
			this._grpOpciones = new qx.ui.groupbox.GroupBox();
			this._grpOpciones.setLayout(new qx.ui.layout.HBox(20).set({alignX:"center"}));
			this._w["btnAgregar"] = new qx.ui.form.Button("Agregar");
			this._w["btnModificar"] = new qx.ui.form.Button("Modificar");
			this._w["btnBorrar"] = new qx.ui.form.Button("Borrar");

			this._grpOpciones.add(this._w["btnAgregar"]);
			this._grpOpciones.add(this._w["btnModificar"]);
			this._grpOpciones.add(this._w["btnBorrar"]);
			this._grpGrid.add(this._grpOpciones);

			this._add(this._grpGrid, {left:0, top:0});
		},
		_getValuesGrid : function ()
		{
			var rpc = new qx.io.remote.Rpc();
			rpc.setTimeout(15000);
			rpc.setUrl("services/");
	        rpc.setServiceName(this._serviceNameApp);
	        if (this._async) {
	        	var context = this;
	        	rpc.callAsync(function (result, ex, id) {
	        		if (ex == null) {
	        			context._grid.getTableModel().setData(result);
	        		} else {
	        			alert(ex);
	        		}
	        	}, context._json.rpcDataGrid);
	        } else {
		        try
		        {
					var result = rpc.callSync(this._json.rpcDataGrid);
					this._grid.getTableModel().setData(result);
				}
				catch (ex)
				{
					alert(ex + " - ");
				}
	        }
		},
		_constructValues : function ()
		{
			for (var obj in this._json) // For que identifica las propiedades de cada columna
			{
				if (this._json[obj].values != undefined)
				{
					if (this._json[obj].values.items != undefined)
					{
						this._addValues(this._w[obj], this._json[obj].values.items, this._json[obj].values.nullValue);
					}
					if (this._json[obj].values.rpc != undefined)
					{
						var rpc = new qx.io.remote.Rpc();
						rpc.setTimeout(10000);
						rpc.setUrl("services/");
				        rpc.setServiceName(this._serviceNameApp);
//				        if (this._async) {
//				        	var context = this;
//				        	rpc.callAsync(function (result, ex, id) {
//				        		if (ex == null) {
////				        			alert("entro!");
//				        			context._addValues(context._w[obj], result.values, result.nullValue);
//				        		} else {
//				        			alert(ex);
//				        		}
//				        	}, context._json[obj].values.rpc);
//				        } else {
					        try {
								var result = rpc.callSync(this._json[obj].values.rpc);
								this._addValues(this._w[obj], result.values, result.nullValue);
							} catch (ex) {
								alert(ex);
							}

//				        }
					}
				}
			}
		},
		_addValues : function (obj, values, nullValue)
		{
			switch (obj.classname)
			{
				case "qx.ui.form.ComboBox" :
				{
					if (nullValue) {
						obj.add(new qx.ui.form.ListItem("").set({model:""}));
					}
					for (var i in values) {
						obj.add(new qx.ui.form.ListItem(values[i].label, values[i].icon).set({model:values[i].value}));
					}
					break;
				}
				case "mutual.ow.ComboBox" :
				{
					if (nullValue) {
						obj.getCombo().add(new qx.ui.form.ListItem("").set({model:""}));
					}
					for (var i in values) {
						obj.addValue(values[i]);
					}
					break;
				}
				default :
				{
					alert("Falta como agregar valores a esta clase: " + obj.classname);
					break;
				}
			}
		},
		_constructEvents : function ()
		{
			this._grid.addListener("dblclick", this._execute_btnModificar, this);
			
			this._w["btnAgregar"].addListener("execute", this._execute_btnAgregar, this);
			this._w["btnModificar"].addListener("execute", this._execute_btnModificar, this);
			this._w["btnBorrar"].addListener("execute", this._execute_btnBorrar, this);
			
			this._w["btnGuardar"].addListener("execute", this._execute_btnGuardar, this);
			this._w["btnCancelar"].addListener("execute", this._execute_btnCancelar, this);
		},
		_execute_btnAgregar : function ()
		{
			if (this._json[this._json.key].object != undefined)
			{
				this._w[this._json.key].focus();
			}
			this._grpGrid.hide();
			this._grpInterface.show();
		},
		_execute_btnModificar : function ()
		{
			if (this._grid.getSelectionModel().getSelectedCount())
			{
				for (var i=0,columnas=this._grid.getTableModel().getColumnCount(); i<=(columnas-1); i++)
				{
					if (this._json[this._json.key].tableView.label == this._grid.getTableModel().getColumnName(i))
					{
						var rpc = new qx.io.remote.Rpc();
						rpc.setTimeout(10000);
						rpc.setUrl("services/");
				        rpc.setServiceName(this._serviceNameApp);
//				        if (this._async) {
//				        	var context = this;
//				        	rpc.callAsync(function (result, ex, id) {
//				        		if (ex == null) {
//				        			for (var obj in context._json) { // For que identifica las propiedades de cada columna
//										if ((context._json[obj].object != undefined) && (result[obj] != undefined)) {
//											context._w[obj].setValue(result[obj]);
//										} else {
//											if ((context._w[obj] != undefined) && (context._w[obj].classname === "qx.core.Object") && (result[obj] != undefined)) {
//												context._w[obj].setUserData(obj, result[obj]);
//											}
//										}
//									}
//									if (context._json[context._json.key].object != undefined) {
//										context._w[context._json.key].setEnabled(false);
//									}
//									context._grpGrid.hide();
//									context._grpInterface.show();
//				        		} else {
//				        			alert(ex);
//				        		}
//				        	}, "btnModificar", context._grid.getTableModel().getValue(i, context._grid.getFocusedRow()));
//				        } else {
							try {
								var result = rpc.callSync("btnModificar", this._grid.getTableModel().getValue(i, this._grid.getFocusedRow()));
								for (var obj in this._json) // For que identifica las propiedades de cada columna
								{
									if ((this._json[obj].object != undefined) && (result[obj] != undefined))
									{
										this._w[obj].setValue(result[obj]);
									}
									else
									{
										if ((this._w[obj] != undefined) && (this._w[obj].classname === "qx.core.Object") && (result[obj] != undefined))
										{
											this._w[obj].setUserData(obj, result[obj]);
										}
									}
								}
								if (this._json[this._json.key].object != undefined)
								{
									this._w[this._json.key].setEnabled(false);
								}
								this._grpGrid.hide();
								this._grpInterface.show();
							} catch (ex) {
								alert(ex);
							}
//				        }
						break;
					}
				}
			}
			else
			{
				alert("Debe seleccionar el registro que desea Modificar");
			}
		},
		_execute_btnBorrar : function ()
		{
			if (this._grid.getSelectionModel().getSelectedCount())
			{
				for (var i=0,columnas=this._grid.getTableModel().getColumnCount(); i<=(columnas-1); i++)
				{
					if (this._json[this._json.key].tableView.label == this._grid.getTableModel().getColumnName(i))
					{
						if (confirm("Esta seguro que desea eliminar el registro seleccionado?"))
						{
							var rpc = new qx.io.remote.Rpc();
							rpc.setTimeout(10000);
							rpc.setUrl("services/");
					        rpc.setServiceName(this._serviceNameApp);
//					        if (this._async) {
//					        	var context = this;
//					        	rpc.callAsync(function (result, ex, id) {
//					        		if (ex == null) {
//										context._getValuesGrid();
//					        		} else {
//					        			alert(ex);
//					        		}
//					        	}, "btnBorrar", context._grid.getTableModel().getValue(i, context._grid.getFocusedRow()));
//					        } else {
						        try {
									var result = rpc.callSync("btnBorrar", this._grid.getTableModel().getValue(i, this._grid.getFocusedRow()));
									this._getValuesGrid();
								} catch (ex) {
									alert(ex);
								}
//					        }
						}
						break;
					}
				}
			}
			else
			{
				alert("Debe seleccionar el registro que desea Borrar");
			}
		},
		_execute_btnGuardar : function ()
		{
			var reg = new Object;
			
			if (this._w[this._json.key].classname === "qx.core.Object")
			{
				reg[this._json.key] = this._w[this._json.key].getUserData(this._json.key);
			}
			else
			{
				reg[this._json.key] = this._w[this._json.key].getValue();
			}

			for (var obj in this._json)
			{
				if ((this._json[obj].object != undefined) && (obj != this._json.key))
				{
					reg[obj] = this._w[obj].getValue();
				}
			}

			var alta_modi = true;
			if (this._w[this._json.key].classname === "qx.core.Object")
			{
				if (this._w[this._json.key].getUserData(this._json.key))
					alta_modi = false;
			}
			else
			{
				if (!this._w[this._json.key].isEnabled())
					alta_modi = false;
			}

			if (alta_modi)
			{
				var accion = "opAlta";
			}
			else
			{
				var accion = "opModificacion";
			}
			var rpc = new qx.io.remote.Rpc();
			rpc.setTimeout(10000);
			rpc.setUrl("services/");
	        rpc.setServiceName(this._serviceNameApp);
//	        if (this._async) {
//	        	var context = this;
//	        	rpc.callAsync(function (result, ex, id) {
//	        		if (ex == null) {
//						context._initWidget();
//	        		} else {
//	        			alert(ex);
//	        		}
//	        	}, accion, reg);
//	        } else {
    	        try {
					var result = rpc.callSync(accion, reg);
					this._initWidget();
		        } catch (ex) {
		        	alert(ex);
		        }
//	        }
		},
		_execute_btnCancelar : function ()
		{
			this._initWidget();
		}
	}
});
